package org.xx.armory.ofs.jpa;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import org.xx.armory.ofs.FileRef;

import java.util.Base64;
import java.util.Optional;

import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;
import static org.xx.armory.ofs.FileRefUtils.hashFile;

@Repository
public interface FileRefRepository
        extends JpaRepository<FileRefPO, Long>, JpaSpecificationExecutor<FileRefPO> {
    static FileRef toFileRef(
            FileRefPO po
    ) {
        if (po == null) {
            return null;
        }

        return new FileRef(
                po.getId(),
                po.getObjectId(),
                po.getFileType(),
                po.getName(),
                po.getSize(),
                po.getLastModifiedTime(),
                trimToEmpty(po.getDescription()),
                !isBlank(po.getBrief()) ? Base64.getDecoder().decode(po.getBrief().trim()) : new byte[0],
                po.getAttributes(),
                hashFile(po.getId(), po.getName())
        );
    }

    Page<FileRefPO> findAllByObjectIdAndFileType(
            long objectId,
            int fileType,
            Pageable pageable
    );

    Optional<FileRefPO> findByObjectIdAndFileTypeAndName(
            long objectId,
            int fileType,
            String name
    );
}
